//
//  NSString+Extension.swift
//  EY.Mtel_ProjectTemplate_Swift
//
//  Created by zxj on 2020/7/27.
//  Copyright © 2020 EY.Mtel. All rights reserved.
//

import UIKit

public extension String {
    var urlEscaped: String {
        return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    }
    
    var utf8Encoded: Data {
        return data(using: .utf8)!
    }
    
    /// 空字符串显示 - - 否则显示字符串本身
    var friendlyString: String {
        return self.isEmpty ? "- -" : self
    }
    
    /// 数字字符串
    ///
    /// - Parameter accuracy: 精度 (保留小数点位数)
    /// - Returns: 数字字符串
    func numStringWith(accuracy: Int) -> String {
        if isEmpty || accuracy < 0 {
            return "- -"
        }
        
        guard let doubleValue = Double(self) else {
            return "- -"
        }
        
        return doubleValue.numStringWith(accuracy: accuracy)
    }

    /// 验证手机号是否有效
    func isValidateMobile() -> Bool {
        let phoneRegex = "^((13[0-9])|(15[^4,\\D])|(17[^4,\\D])|(18[0,0-9]))\\d{8}$"
        let phoneTest = NSPredicate.init(format: "SELF MATCHES %@", phoneRegex)
        return phoneTest.evaluate(with: self)
    }
    
    func toUIColor() -> UIColor {
        var cString = self.uppercased().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        let length = (cString as NSString).length
        if (length < 6 || length > 7 || (!cString.hasPrefix("#") && length == 7)){
            return UIColor.white
        }
        if cString.hasPrefix("#"){
            cString = (cString as NSString).substring(from: 1)
        }
        var range = NSRange()
        range.location = 0
        range.length = 2
        let rString = (cString as NSString).substring(with: range)
        range.location = 2
        let gString = (cString as NSString).substring(with: range)
        range.location = 4
        let bString = (cString as NSString).substring(with: range)
        var r:UInt32 = 0,g:UInt32 = 0,b:UInt32 = 0
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)
        return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0)
    }
    
}
